import { IconDouyin } from '@/components/icon';
import IconToutiao from '@/components/icon/IconToutiao';
import IconWeibo from '@/components/icon/IconWeibo';
import { saveInitTophubOperate } from '@/services/api/api-tophub-operate';
import {
  ActionType,
  DrawerForm,
  ProFormCascader,
  ProFormInstance,
  ProFormTextArea,
} from '@ant-design/pro-components';
import { useAccess } from '@umijs/max';
import { Cascader, Divider, Flex, message, Space, Spin, Tag, Typography } from 'antd';
import FormItem from 'antd/es/form/FormItem';
import React, { useRef, useState } from 'react';
import UploadDragger from '../components/UploadDragger';
interface AddOperateAssociationEditProps {
  selectHotQuery: TophubHotRankData.HotQuery;
  onRefurbish: (values: any) => boolean;
}

const AddOperateAssociationEdit: React.FC<AddOperateAssociationEditProps> = ({
  selectHotQuery,
  onRefurbish,
}) => {
  const access = useAccess();

  const actionRef = useRef<ActionType>();

  const formRef = useRef<ProFormInstance>();

  const [loading, setLoading] = useState(false);

  const [saveInit, setSaveInitState] = useState<TophubOperateData.OperateSaveInit>();

  const [selectsources, setSelectsourcesState] = useState<
    TophubOperateData.OperateSaveInitSources[]
  >([]);

  /**
   * 加载 保存初始化数据
   * @param key
   */
  const loadSaveInitTophubRecord = async () => {
    setLoading(true);
    try {
      const response = await saveInitTophubOperate({
        hotType: selectHotQuery.type,
      });
      const { code, data } = response;
      if (code === 0) {
        let sourceIds = selectHotQuery.sources.map((item) => item.value);

        let sources = data.sources.map((item) => {
          return {
            ...item,
            children: item.children.map((e) => {
              if (sourceIds.includes(e.value)) {
                return {
                  ...e,
                  disabled: true,
                };
              } else {
                return e;
              }
            }),
          };
        });

        setSaveInitState({
          ...data,
          sources: sources,
        });
        setLoading(false);
      }
    } catch (error) {}
  };

  const containerHot = () => {
    let hotRankType;
    let authorTitle;

    if (selectHotQuery.type == 1) {
      hotRankType = {
        icon: <IconWeibo width={18} height={21} />,
        name: '微博热搜',
        authorTitle: '主持人',
      };
    } else if (selectHotQuery.type == 2) {
      hotRankType = {
        icon: <IconDouyin width={18} height={21} />,
        name: '抖音热榜',
        authorTitle: '作者',
      };
    } else if (selectHotQuery.type == 4) {
      hotRankType = {
        icon: <IconToutiao width={18} height={21} />,
        name: '头条热搜',
        authorTitle: '作者',
      };
    }

    return (
      <>
        <Space align="start">
          <Space align={'start'}>
            {hotRankType?.icon}
            {hotRankType?.name}
          </Space>
          <Tag color={selectHotQuery?.isCity == 0 ? 'error' : 'gold'}>
            {selectHotQuery?.isCity == 0 ? '全国' : '重庆'}：{selectHotQuery.topIndex}
          </Tag>
          <Typography.Title copyable level={5}>
            <a>{selectHotQuery.name}</a>
          </Typography.Title>
        </Space>
        <Flex
          justify={'space-between'}
          align={'center'}
          style={{
            width: '100%',
          }}
        >
          <Space align={'start'} size="large">
            <span>
              <Typography.Text type="secondary">{hotRankType?.authorTitle}：</Typography.Text>
              {selectHotQuery?.author ? selectHotQuery?.author : '暂无'}
            </span>
            <span>
              <Typography.Text type="secondary">采录时间：</Typography.Text>
              {selectHotQuery?.insertTime}
            </span>
          </Space>
          <a href={selectHotQuery?.url} target="_blank">
            原文链接
          </a>
        </Flex>
      </>
    );
  };

  return (
    <DrawerForm
      title="编辑"
      trigger={<a>编辑</a>}
      drawerProps={{
        maskClosable: false,
        destroyOnClose: true,
        width: 650,
      }}
      formRef={formRef}
      onOpenChange={async (visible) => {
        if (visible) {
          loadSaveInitTophubRecord();
        } else {
        }
      }}
      initialValues={{
        addSources: selectHotQuery?.addSources?.map((item) => {
          return item?.map((e) => {
            return e.value;
          });
        }),
        remarks: selectHotQuery?.remarks,
        attachments: selectHotQuery?.attachments,
      }}
      onValuesChange={(values) => {}}
      onFinish={async (values) => {
        if (selectsources.length == 0) {
          message.warning('请选择关联账号');
          return;
        }

        console.log('====', values);

        return onRefurbish({
          hotId: selectHotQuery.id,
          addSources: selectsources,
          remarks: values.remarks,
          attachments: values?.attachments?.filter((item) => item.status == 'done'),
        });
      }}
    >
      {loading ? (
        <Flex
          style={{
            marginTop: '50px',
          }}
          justify={'center'}
          align={'flex-start'}
        >
          <Spin />
        </Flex>
      ) : (
        <>
          {containerHot()}
          <Divider />
          <ProFormCascader
            label="关联账号"
            name="addSources"
            placeholder="请选择关联账号"
            rules={[
              {
                required: true,
                message: '请选择关联账号!',
              },
            ]}
            fieldProps={{
              multiple: true,
              options: saveInit?.sources,
              showSearch: true,
              showCheckedStrategy: Cascader.SHOW_CHILD,
              onChange: (value: any, selectOptions: any[]) => {
                setSelectsourcesState(selectOptions);
              },
            }}
          />
          <ProFormTextArea
            name="remarks"
            label="备注"
            placeholder="请输入"
            fieldProps={{
              rows: 3,
            }}
          />
          <FormItem
            name="attachments"
            label={
              <span
                style={{
                  marginLeft: 11,
                }}
              >
                附件
              </span>
            }
          >
            <UploadDragger
              dragger={true}
              onPreview={(file) => {}}
              access={{
                isPicture: access.热搜热榜x配置x管理员 || access.热搜热榜x配置x运营员,
                isVideo: access.热搜热榜x配置x管理员 || access.热搜热榜x配置x运营员,
                isOffice: access.热搜热榜x配置x管理员 || access.热搜热榜x配置x运营员,
                isOther: access.热搜热榜x配置x管理员 || access.热搜热榜x配置x运营员,
              }}
              url="/tophub/attachment/save"
              maxCount={10}
            />
          </FormItem>
        </>
      )}
    </DrawerForm>
  );
};
export default AddOperateAssociationEdit;
